package com.gscitysfy.cus.drain.config;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.gscitysfy.cloudfrmwk.security.definition.core.HerodotusUserDetails;
import com.gscitysfy.cloudfrmwk.security.utils.SecurityUtils;
import groovy.util.logging.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author Administrator
 * @description: sql数据自动注入
 **/
@Slf4j
@Component
public class MybatisPlusObjectHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(MybatisPlusObjectHandler.class);

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                LOGGER.info("start install fill");
                this.strictInsertFill(metaObject,"cmAddtime",Date.class, new Date());
                this.strictInsertFill(metaObject,"cmUptime", Date.class, new Date());
                this.strictInsertFill(metaObject, "cmUsable", Boolean.class, false);
                HerodotusUserDetails principal = SecurityUtils.getPrincipal();
                if(Objects.nonNull(principal)){
                    this.strictInsertFill(metaObject,"cmCreator",String.class, principal.getName());
                    this.strictInsertFill(metaObject,"cmModifier",String.class, principal.getName());
                }
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                LOGGER.info("start update fill");
                this.setFieldValByName("cmUptime",new Date(),metaObject);
                HerodotusUserDetails principal = SecurityUtils.getPrincipal();
                if(Objects.nonNull(principal)){
                    this.strictInsertFill(metaObject,"cmModifier",String.class, principal.getName());
                }
            }
        };
    }


}
